'''
Created on Aug 8, 2011

@author: bstar
'''
from dopplershift.backend.db import DSBackendDatabase
from twisted.internet import reactor
import logging
import txmongo
from dopplershift.core.utils.logger import DSLogging
logger = logging.getLogger(__name__)

class DSMongodbBackend(DSBackendDatabase):
    name = "mongodb"
    def configure(self, config):
        DSBackendDatabase.configure(self, config)
        self._host = config.get("mongodb_host")
        self._port = int(config.get("mongodb_port"))
        d = txmongo.MongoConnection(self._host, self._port)
        self._default_db_name = config.get("mongodb_database")
        d.addCallback(self._connected)
        d.addErrback(self._disconnected)
        logger.debug("Connect to mongodb")
        
    def _connected(self, connection):
        logger.debug("Factory connected to mongodb host %s:%s"%(self._host, self._port))
        self._connection = connection
    def _disconnected(self, err):
        print err
    def getDatabase(self, database_name):
        return getattr(self._connection, database_name)
    def getCollection(self, collection, database=None):
        if database is None:
            database = self._default_db_name
        return getattr(getattr(self._connection, database), collection)